using Admin2025.Application.Events;
using MediatR;
using Microsoft.Extensions.Logging;

namespace Admin2025.Application.EventHandlers;

//用户创建事件处理器 - 发送欢迎邮件

public class UserCreatedWelcomeHandler : INotificationHandler<UserCreatedNotification>
{
    private readonly ILogger<UserCreatedWelcomeHandler> _logger;
    public UserCreatedWelcomeHandler(ILogger<UserCreatedWelcomeHandler> logger)
    {
        _logger = logger;
    }

    public async Task Handle(UserCreatedNotification notification, CancellationToken cancellationToken)
    {
        var userEvent = notification.UserCreatedEvent;

        _logger.LogInformation("开始发送欢迎邮件：事件ID={EventId},用户ID={UserId}，用户名={Username}",
            userEvent.EventId, userEvent.UserId, userEvent.Username);
        try
        {
            await SendWelcomeEmail(userEvent.Username);
            _logger.LogInformation("邮件发送成功：用户ID={UserId}", userEvent.UserId);
        }
        catch (Exception ex)
        {

            _logger.LogError(ex, "邮件发送：用户ID={UserId}", userEvent.UserId);
        }
    }

    private async Task SendWelcomeEmail(string username)
    {
        //模拟发送邮件的异步操作
        await Task.Delay(100);
        _logger.LogInformation("邮件已发送给用户：{Username}", username);
    }
}